package com.b2c.common.third.express;

import static com.b2c.common.utils.HttpUtil.map2Url;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.b2c.common.utils.Md5Util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Description: pbd add 2019/6/13 16:00
 */
public class KuaiDi100ExpressClient {
    private static Logger log = LoggerFactory.getLogger(KuaiDi100ExpressClient.class);
    private static final String DEFAULT_CHARSET = "UTF-8";
    private static String key = "Ywq0uOo6nTEx";
    private static String serret = "6880dfb586d1442a9bbfd523fc30127f";

    /**
     * post请求
     *
     * @param sendUrl 请求地址
     * @param params  请求参数
     */
    public static HttpResponse<String> doPost(String sendUrl, String params) {
        try {
            HttpClient client = HttpClient.newBuilder().build();
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(sendUrl)).header("Content-Type", "application/x-www-form-urlencoded").POST(HttpRequest.BodyPublishers.ofString(params))
                    .build();
            return client.send(request, HttpResponse.BodyHandlers.ofString());
        } catch (Exception e) {
            log.error("ExpressClient doPost exception:" + e);
        }
        return null;

    }

    /**
     * 参数拼接，字符加密
     *
     * @param params
     * @param clientSecret
     * @return
     */
    public static String buildSign(Map<String, String> params, String
            clientSecret) {
        Map<String, String> paramsMap = null;
        if (params instanceof TreeMap) {
            paramsMap = params;
        } else {
            paramsMap = new TreeMap<String, String>();
            paramsMap.putAll(params);//加入所有参数
        }
        StringBuffer strBuffer = new StringBuffer(clientSecret);
        Set<Map.Entry<String, String>> entrySet = paramsMap.entrySet();
        for (Map.Entry<String, String> entry : entrySet) {
            strBuffer.append(entry.getKey()).append(entry.getValue());
        }
        strBuffer.append(clientSecret);
        return Md5Util.MD5(strBuffer.toString());
    }

    public static String buildSignObj(Map<String, Object> params, String
            clientSecret) {
        Map<String, Object> paramsMap = null;
        if (params instanceof TreeMap) {
            paramsMap = params;
        } else {
            paramsMap = new TreeMap<String, Object>();
            paramsMap.putAll(params);//加入所有参数
        }
        StringBuffer strBuffer = new StringBuffer(clientSecret);
        Set<Map.Entry<String, Object>> entrySet = paramsMap.entrySet();
        for (Map.Entry<String, Object> entry : entrySet) {
            strBuffer.append(entry.getKey()).append(entry.getValue());
            System.out.println(entry.getValue());
        }
        strBuffer.append(clientSecret);
        return Md5Util.MD5(strBuffer.toString());
    }
    public static String buildSign2(Map<String, Object> params, String clientSecret) {
        Map<String, Object> newMap=new HashMap<>();
        Set<Map.Entry<String, Object>> newSet = params.entrySet();
        for (Map.Entry<String, Object> entry : newSet) {
            if(entry.getValue().getClass().equals(JSONObject.class)){
                JSONObject objJson = JSON.parseObject(entry.getValue().toString());
                newMap.put(entry.getKey(),"");
                Iterator<String> it = objJson.keySet().iterator();
                while(it.hasNext()){
                    String key = it.next();
                    if (objJson.get(key) instanceof JSONObject) {
                        getJSONObject((JSONObject)objJson.get(key),newMap);
                    } else if (objJson.get(key) instanceof JSONArray) {
                        newMap.put(key,"");
                        getJSONArray((JSONArray)objJson.get(key),newMap);
                    }
                }
            }
            if(entry.getValue() instanceof String ){
                newMap.put(entry.getKey(),entry.getValue());
            }
        }

        Map<String, Object> paramsMap = null;
        if (newMap instanceof TreeMap) {
            paramsMap = newMap;
        } else {
            paramsMap = new TreeMap<>();
            paramsMap.putAll(newMap);//加入所有参数
        }
        StringBuffer strBuffer = new StringBuffer(clientSecret);
        Set<Map.Entry<String, Object>> entrySet = paramsMap.entrySet();
        for (Map.Entry<String, Object> entry : entrySet) {
            System.out.println(entry.getKey());
            strBuffer.append(entry.getKey()).append(entry.getValue().toString());
/*            StringBuffer buffer = new StringBuffer();
            if(entry.getValue().getClass().equals(JSONObject.class)){
                JSONObject objJson = JSON.parseObject(entry.getValue().toString());
                buffer.append(entry.getKey());
                Iterator<String> it = objJson.keySet().iterator();
                while(it.hasNext()){
                    String key = it.next();
                    if (objJson.get(key) instanceof JSONObject) {
                        buffer.append(key).append(objJson.getString(key));
                    } else if (objJson.get(key) instanceof JSONArray) {
                        buffer.append(key);
                        JSONArray arrayObj = (JSONArray) objJson.get(key);
                        buffer.append(getJSONArray(arrayObj));
                    }
                }
                System.out.println(buffer.toString());
            }
            strBuffer.append(buffer);
            if(entry.getValue() instanceof String ){
                System.out.println(entry.getKey());
                strBuffer.append(entry.getKey()).append(entry.getValue());
            }*/
        }
        strBuffer.append(clientSecret);
        return Md5Util.MD5(strBuffer.toString());
    }

    public static StringBuffer getJSONArray(JSONArray json,Map<String, Object> map) {
        StringBuffer stringBuffer = new StringBuffer();
        if (json != null ) {
            Iterator i1 = json.iterator();
            while (i1.hasNext()) {
                Object key = i1.next();
                if (key instanceof  JSONObject) {
                    JSONObject innerObject = (JSONObject) key;
                    getJSONObject(innerObject,map);
                    //stringBuffer.append(getJSONObject(innerObject));
                }
        }
    }
        return stringBuffer;
    }

    public static StringBuffer getJSONObject(JSONObject json,Map<String, Object> map) {
        StringBuffer stringBuffer = new StringBuffer();
        if (json != null ) {
            Iterator<String> it = json.keySet().iterator();
            while(it.hasNext()){
                String key = it.next();
                if (json.get(key) instanceof String) {
                    //stringBuffer.append(key).append(json.getString(key));
                    map.put(key,json.getString(key));
                }
            }
        }
        return stringBuffer;
    }

    /**
     * 获取快递100 code
     *
     * @return
     */
    public static String getCode() {
        try {
            Map<String, String> params = new HashMap<>();
            params.put("client_id", key);
            params.put("response_type", "code");
            params.put("redirect_uri", "http://localhost:8089/callback/kuaidi100");// "http://wms.huayikeji.com/callback/kuaidi100");
            params.put("timestamp", String.valueOf(System.currentTimeMillis()));
            params.put("sign", buildSign(params, serret));
            return "https://b.kuaidi100.com/open/oauth/authorize?" + map2Url(params);
        } catch (Exception e) {

        }
        return null;
    }

    /**
     * 订单导入快递100
     *
     * @param token
     */
    public static void exportOrder(String token) {
        try {
            Map<String, String> params = new HashMap<>();
            params.put("appid", "Ywq0uOo6nTEx");
            params.put("access_token", token);
            JSONObject json = new JSONObject();
            json.put("recMobile", "13077847784");
            json.put("recCompany", "金蝶集团");
            json.put("sendCompany", "快递 100");
            json.put("recName", "刘生");
            json.put("recAddr", "安徽亳州涡阳县牌坊镇 陈兰大药房");
            json.put("reccountry", "中国");
            json.put("sendMobile", "18675586237");
            json.put("sendName", "刘三石");
            json.put("sendAddr", "广东深圳南山区科技南十二路金蝶软件园");
            json.put("orderNum", "20180612001");
            json.put("kuaidiCom", "yunda");
            json.put("weight", 1);
            params.put("data", JSON.toJSONString(json));
            params.put("timestamp", String.valueOf(System.currentTimeMillis()));
            params.put("sign", KuaiDi100ExpressClient.buildSign(params, "6880dfb586d1442a9bbfd523fc30127f"));
            HttpResponse<String> response = doPost("https://b.kuaidi100.com/v6/open/api/send", map2Url(params));
            if (response.statusCode() == 200) {
                JSONObject obj = JSONObject.parseObject(response.body());
                System.out.println(obj);
            }
        } catch (Exception e) {
            log.error("exportOrder exception:" + e);
        }
    }

    /**
     * 快递100云打印
     */
    public static void printTask() {
        try {
            String url = "http://poll.kuaidi100.com/printapi/printtask.do?method=eOrder";
            Map<String, String> params = new HashMap<>();
            //params.put("method", "eOrder");
            params.put("key", "HemHbdOY1667");
            JSONObject p = new JSONObject();
            p.put("type", "10");
            p.put("partnerId", "4398900340329");//电子面单客户账户或月结账号
            p.put("partnerKey", "dFVsaGlNYW1LdU0yMkx1bHR5OVJHRTFqeUkyaktxbHhNdzFVcnhXY2dXT0dYRkFyWG54ZThNU1JIUzIzWEN4aw==");
            p.put("kuaidicom", "yunda");

            JSONObject recMan = new JSONObject();
            recMan.put("name", "pbd");//收件人姓名
            recMan.put("mobile", "13077847784");
            recMan.put("province", "广东省");
            recMan.put("city", "深圳市");
            recMan.put("district", "南山区");
            recMan.put("addr", "大冲商务中心");
            recMan.put("printAddr", "广东深圳市深圳市南山区科技南十二路2号金蝶软件园");

            p.put("recMan", recMan);

            JSONObject sendMan = new JSONObject();
            sendMan.put("name", "华衣");//寄件人姓名
            sendMan.put("mobile", "13077847784");
            sendMan.put("province", "广东省");
            sendMan.put("city", "深圳市");
            sendMan.put("district", "南山区");
            sendMan.put("addr", "大冲商务中心");
            sendMan.put("printAddr", "广东深圳市深圳市南山区科技南十二路2号金蝶软件园");

            p.put("sendMan", sendMan);

            p.put("count", "1");
            p.put("weight", "0.5");
            p.put("volumn", "100.20");
            p.put("tempid", "2069632");//打印摸版配置信息
            p.put("siid", "dayin");//打印设备，通过打印机输出的设备码进行获取

            p.put("callBackUrl", "http://localhost:8089/callback/printTask");

            System.out.println(p.toJSONString());
            String now = String.valueOf(System.currentTimeMillis());
            //params.put("param", p.toJSONString());
            params.put("t", now);
            params.put("key", "HemHbdOY1667");
            StringBuilder builder = new StringBuilder(p.toJSONString());
            builder.append(now);
            builder.append("HemHbdOY1667");
            builder.append("beb93369e66d4c3f8ecfb8074a9bb9a6");
            params.put("sign", Md5Util.MD5(builder.toString()));

            System.out.println(map2Url(params));

/*            HttpResponse<String> response = doPost(url,map2Url(params));
            if(response.statusCode()==200){
                JSONObject obj= JSONObject.parseObject(response.body());
                System.out.println(obj);
            }*/
        } catch (Exception e) {
            log.error("快递100云打印 printTask Exception：" + e);
        }

    }


    /**
     * 快递100云打印
     */
    public static void printImg_test() {
        try {
            String url = "http://poll.kuaidi100.com/printapi/printtask.do?method=getPrintImg";
            Map<String, String> params = new HashMap<>();
            //params.put("method", "getPrintImg");
            params.put("key", "HemHbdOY1667");
            String now = String.valueOf(System.currentTimeMillis());
            params.put("t", now);

            JSONObject param = new JSONObject();
            param.put("type", "10");
            param.put("partnerId", "4398900340329");//电子面单客户账户或月结账号
            param.put("partnerKey", "dFVsaGlNYW1LdU0yMkx1bHR5OVJHRTFqeUkyaktxbHhNdzFVcnhXY2dXT0dYRkFyWG54ZThNU1JIUzIzWEN4aw==");

            //发件人
            param.put("recManName", "pbd");
            param.put("recManMobile", "13077847784");
            param.put("recManProvince", "广东省");
            param.put("recManCity", "深圳市");
            param.put("recManDistrict", "南山区");
            param.put("recManAddr", "科技南十二路2号金蝶软件园");
            param.put("recManPrintAddr", "广东深圳市深圳市南山区科技南十二路2号金蝶软件园");

            //收件人
            param.put("sendManName", "pbd");
            param.put("sendManMobile", "13077847784");
            param.put("sendManProvince", "广东省");
            param.put("sendManCity", "深圳市");
            param.put("sendManDistrict", "南山区");
            param.put("sendManAddr", "科技南十二路2号金蝶软件园");
            param.put("sendManPrintAddr", "广东深圳市深圳市南山区科技南十二路2号金蝶软件园");

            //快递信息
            param.put("cargo", "测试打印面单图片");
            param.put("count", "1");
            param.put("weight", "0.5");
            param.put("volumn", "4000");
            param.put("tempid", "5ada972099e8483faef7b33113a0dc6f");//面单id
            param.put("kuaidicom", "yunda");//快递公司
            param.put("net", "cainiao");
            param.put("needChild", "0");
            param.put("needBack", "0");
            param.put("op", "0");
            param.put("resultv2", "0");


            System.out.println(param.toJSONString());
            //params.put("param", p.toJSONString());
            StringBuilder builder = new StringBuilder(param.toJSONString());
            builder.append(now);
            builder.append("HemHbdOY1667");
            builder.append("beb93369e66d4c3f8ecfb8074a9bb9a6");
            //String sign=Md5Util.MD5(builder.toString());
            params.put("sign", Md5Util.MD5(builder.toString()));

            StringBuilder builder_1 = new StringBuilder("&param=" + param.toJSONString());
            builder_1.append("&" + map2Url(params));

            System.out.println(builder_1.toString());

            HttpResponse<String> response = doPost(url, builder_1.toString());
            if (response.statusCode() == 200) {
                JSONObject obj = JSONObject.parseObject(response.body());
                System.out.println(obj);
            }
        } catch (Exception e) {
            log.error("快递100云打印 printTask Exception：" + e);
        }

    }

    /**
     * 快递100云打印
     */
    public static void printImg() {
        try {
            String url = "http://poll.kuaidi100.com/printapi/printtask.do?method=getPrintImg";
            Map<String, String> params = new HashMap<>();
            //params.put("method", "getPrintImg");
            params.put("key", "HemHbdOY1667");
            String now = String.valueOf(System.currentTimeMillis());
            params.put("t", now);

            JSONObject param = new JSONObject();
            param.put("type", "10");
            param.put("partnerId", "4398900340329");//电子面单客户账户或月结账号
            param.put("partnerKey", "dFVsaGlNYW1LdU0yMkx1bHR5OVJHRTFqeUkyaktxbHhNdzFVcnhXY2dXT0dYRkFyWG54ZThNU1JIUzIzWEN4aw==");

            //发件人
            param.put("recManName", "pbd");
            param.put("recManMobile", "13077847784");
/*            param.put("recManProvince","广东省");
            param.put("recManCity","深圳市");
            param.put("recManDistrict","南山区");
            param.put("recManAddr","科技南十二路2号金蝶软件园");*/
            param.put("recManPrintAddr", "广东深圳市深圳市南山区科技南十二路2号金蝶软件园");

            //收件人
            param.put("sendManName", "pbd");
            param.put("sendManMobile", "13077847784");
            param.put("sendManProvince", "广东省");
            param.put("sendManCity", "深圳市");
            param.put("sendManDistrict", "南山区");
            param.put("sendManAddr", "科技南十二路2号金蝶软件园");
            param.put("sendManPrintAddr", "广东深圳市深圳市南山区科技南十二路2号金蝶软件园");

            //快递信息
            param.put("cargo", "测试打印面单图片");
            param.put("count", "1");
            param.put("weight", "0.5");
            param.put("volumn", "4000");
            param.put("tempid", "5ada972099e8483faef7b33113a0dc6f");//面单id
            param.put("kuaidicom", "yunda");//快递公司
            param.put("net", "cainiao");
            param.put("needChild", "0");
            param.put("needBack", "0");
            param.put("op", "0");
            param.put("resultv2", "0");


            System.out.println(param.toJSONString());
            //params.put("param", p.toJSONString());
            StringBuilder builder = new StringBuilder(param.toJSONString());
            builder.append(now);
            builder.append("HemHbdOY1667");
            builder.append("beb93369e66d4c3f8ecfb8074a9bb9a6");
            //String sign=Md5Util.MD5(builder.toString());
            params.put("sign", Md5Util.MD5(builder.toString()));

            StringBuilder builder_1 = new StringBuilder("&param=" + param.toJSONString());
            builder_1.append("&" + map2Url(params));

            System.out.println(builder_1.toString());

            HttpResponse<String> response = doPost(url, builder_1.toString());
            if (response.statusCode() == 200) {
                JSONObject obj = JSONObject.parseObject(response.body());
                System.out.println(obj);
            }
        } catch (Exception e) {
            log.error("快递100云打印 printTask Exception：" + e);
        }

    }

    /**
     * 对字节数组字符串进行Base64解码并生成图片
     *
     * @param base64
     * @param path
     * @return
     * @throws IOException
     */
    public static boolean base64ToImageFile(String base64, String path) throws IOException {
        System.out.println(base64.length());
        // 生成jpeg图片
        try {
            OutputStream out = new FileOutputStream(path);
            return base64ToImageOutput(base64, out);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 处理Base64解码并输出流
     *
     * @param base64
     * @param out
     * @return
     */
    public static boolean base64ToImageOutput(String base64, OutputStream out) throws IOException {
        if (base64 == null) { // 图像数据为空
            return false;
        }
        try {
            // Base64解码
            byte[] bytes = org.apache.commons.codec.binary.Base64.decodeBase64(base64);
            for (int i = 0; i < bytes.length; ++i) {
                if (bytes[i] < 0) {// 调整异常数据
                    bytes[i] += 256;
                }
            }
            // 生成jpeg图片
            out.write(bytes);
            out.flush();
            return true;
        } finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void printImgTest() {
        try {
            Map<String, String> params = new HashMap<>();
            params.put("method", "getPrintImg");
            params.put("key", "HemHbdOY1667");
            String now = String.valueOf(System.currentTimeMillis());
            params.put("t", now);
            JSONObject param = new JSONObject();
            param.put("type", "10");
            param.put("partnerId", "4398900340329");//电子面单客户账户或月结账号
            param.put("partnerKey", "dFVsaGlNYW1LdU0yMkx1bHR5OVJHRTFqeUkyaktxbHhNdzFVcnhXY2dXT0dYRkFyWG54ZThNU1JIUzIzWEN4aw==");

            //发件人
            param.put("recManName", "pbd");
            param.put("recManMobile", "13077847784");
            param.put("recManProvince", "广东省");
            param.put("recManCity", "深圳市");
            param.put("recManDistrict", "南山区");
            param.put("recManAddr", "科技南十二路2号金蝶软件园");
            param.put("recManPrintAddr", "广东深圳市深圳市南山区科技南十二路2号金蝶软件园");

            //收件人
            param.put("sendManName", "pbd");
            param.put("sendManMobile", "13077847784");
            param.put("sendManProvince", "广东省");
            param.put("sendManCity", "深圳市");
            param.put("sendManDistrict", "南山区");
            param.put("sendManAddr", "科技南十二路2号金蝶软件园");
            param.put("sendManPrintAddr", "广东深圳市深圳市南山区科技南十二路2号金蝶软件园");

            //快递信息
            param.put("cargo", "测试打印面单图片");
            param.put("count", "1");
            param.put("weight", "0.5");
            param.put("volumn", "4000");
            param.put("tempid", "5ada972099e8483faef7b33113a0dc6f");//面单id
            param.put("kuaidicom", "yunda");//快递公司
            param.put("net", "cainiao");
            param.put("needChild", "0");
            param.put("needBack", "0");
            param.put("op", "0");
            param.put("resultv2", "0");
            param.put("payType", "SHIPPER");
            param.put("expType", "标准快递");
            param.put("orderId", "test001");
            StringBuilder builder = new StringBuilder(param.toJSONString());
            builder.append(now);
            builder.append("HemHbdOY1667");
            builder.append("beb93369e66d4c3f8ecfb8074a9bb9a6");
            params.put("sign", Md5Util.MD5(builder.toString()));
            StringBuilder builder_1 = new StringBuilder("&" + map2Url(params));
            builder_1.append("&param=" + param.toJSONString());
            System.out.println("https://poll.kuaidi100.com/manager/debugtools/eprint/rsimg.do" + builder_1.toString());
            HttpResponse<String> response = doPost(":https://poll.kuaidi100.com/manager/debugtools/eprint/rsimg.do", builder_1.toString());
            if (response.statusCode() == 200) {
                JSONObject obj = JSONObject.parseObject(response.body());
                System.out.println(obj);
            }
        } catch (Exception e) {
            log.error("快递100云打印 printTask Exception：" + e);
        }
    }

//     public static void main(String[] args) {
//         String str = "[\\\"/afasfdasf\n\\\"]";
// /*        String str1 = str.replace("[\\\"","");
//         String str2=str1.replace("\"]","");
//         System.out.println(str2);*/
//         // JSONObject obj= JSON.parseObject(str);
//         //System.out.println(obj.getString("imgBase64"));
//         //JSONArray array =JSONArray.parseArray(str);
//         //System.out.println(array);
//         //printTask();
//         printImg();
//     }

}
